/*
 * Copyright 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package client;

import com.google.gwt.user.client.ui.*;


/**
 * A sample toolbar for use with {@link RichTextArea}. It provides a simple UI
 * for all rich text formatting, dynamically displayed only for the available
 * functionality.
 */
public class CssController {

    private EventListener listener = new EventListener();
    private RichTextArea richText;
    private TextArea debug;
    private TextArea pasteArea;
    private DialogBox dialogBox;

    /**
     * Creates a new toolbar that drives the given rich text area.
     *
     * @param richText the rich text area to be controlled
     */
    public CssController(RichTextArea richText) {
        this(richText, null);
    }

    public CssController(RichTextArea richText, TextArea debug) {
        this.richText = richText;
        this.debug = debug;
        if (richText.getBasicFormatter() != null) {
            richText.addKeyboardListener(listener);
        }
    }

    protected void doEnterStuff() {
        //setHTML(getHTML().replaceAll("<P>&nbsp;</P>", "").replaceAll("<P>", "").replaceAll("</P>", "").replaceAll("\n", "<br>"));
    }

    private void updateStatus() {
        if (debug != null) {
            debug.setText(richText.getHTML());
        }
    }

    public void setHtml(String html) {
        richText.setHTML(html);
    }

    public String getHtml() {
        return richText.getHTML();
    }

    public void doPaste() {
        if (dialogBox == null) {
            dialogBox = createDialogBox();
        }
        CssHelper.preInsert(richText);
        dialogBox.center();
        pasteArea.selectAll();
        pasteArea.setFocus(true);
    }

    /**
     * We use an inner EventListener class to avoid exposing event methods on the
     * RichTextToolbar itself.
     */

    private class EventListener implements KeyboardListener {

        public void onKeyDown(Widget sender, char keyCode, int modifiers) {
            if ('V' == keyCode && MODIFIER_CTRL == modifiers) {
                doPaste();
            }
        }

        public void onKeyPress(Widget sender, char keyCode, int modifiers) {
        }

        public void onKeyUp(Widget sender, char keyCode, int modifiers) {
            if (sender == richText) {
                if (KEY_ENTER == keyCode) {
                    doEnterStuff();
                }
                updateStatus();
            }
        }
    }

    public void doLink(String link, String extra) {
        if (link != null) {
            replace(CssHelper.toLink(richText, link, extra));
        }
    }

    public void doUnLink() {
        richText.getExtendedFormatter().removeLink();
    }

    public void insert(String toInsert) {
        if (toInsert != null) {
            replace(CssHelper.insert(richText, toInsert));
        }
    }

    public void doCss(String cssClass) {
        replace(CssHelper.toCss(richText, cssClass));
    }

    private void replace(String replace) {
        richText.setHTML(replace);
        richText.setFocus(true);
        updateStatus();
    }


    /**
     * Create the dialog box for this example.
     *
     * @return the new dialog box
     */
    private DialogBox createDialogBox() {
        // Create a dialog box and set the caption text
        final DialogBox dialogBox = new DialogBox();
        dialogBox.setText("Paste");

        // Create a table to layout the content
        VerticalPanel dialogContents = new VerticalPanel();
        dialogContents.setSpacing(4);
        dialogBox.setWidget(dialogContents);

        // Add a close button at the bottom of the dialog
        Button pasteButton = new Button("Paste", new ClickListener() {
            public void onClick(Widget sender) {
                doPaste(dialogBox);
            }
        });

        pasteArea = new TextArea();
        pasteArea.setSize("400px", "250px");
        dialogContents.add(pasteArea);

        pasteArea.addKeyboardListener(new KeyboardListenerAdapter() {
            public void onKeyDown(Widget sender, char keyCode, int modifiers) {
                if (keyCode == KeyboardListener.KEY_ENTER) {
                    doPaste(dialogBox);
                }
            }
        });

        dialogContents.add(pasteButton);
        dialogContents.setCellHorizontalAlignment(pasteButton, HasHorizontalAlignment.ALIGN_RIGHT);

        // Return the dialog box
        return dialogBox;
    }

    private void doPaste(DialogBox dialogBox) {
        String toInsert = pasteArea.getText();
        replace(CssHelper.postInsert(richText, toInsert == null ? "" : toInsert.replaceAll("\n", "<br />")));
        dialogBox.hide();
    }
}